package com.es.esapi.utils;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import org.junit.Test;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;


public class PdfConvertUtil {


    /*
    读取pdf文字
     */
    @Test
    public void readPdfTextTest(String filename) throws IOException {

        byte[] bytes = getBytes(filename);
        //加载PDF文档
        PDDocument document = PDDocument.load(bytes);
        readText(document);
        System.out.println("readPdfTextTest");
        System.out.println(document);
    }



    /**
     * 获取当前运行时间，以便设置生成的文件名
     */

    public String gettime() {
        Date date = new Date(); // this object contains the current date value
        SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy-HH-mm");
        String time=formatter.format(date);
        return time;
    }


    /**
     * pdf文件读取并转成txt文件
     */


    public void readText(PDDocument document) throws IOException {
        PDFTextStripper stripper = new PDFTextStripper();
        String text = stripper.getText(document);
        String time=gettime();
        FileWriter fw = new FileWriter("C://solve//txt//"+time+".txt");//txt文件存储位置

        fw.write(text);
        fw.close();

    }






    /*
    将文件转换为byte数组
     */
    private byte[] getBytes(String filePath) {
        byte[] buffer = null;
        try {
            File file = new File(filePath);
            FileInputStream fis = new FileInputStream(file);
            ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
            byte[] b = new byte[1000];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
            buffer = bos.toByteArray();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer;
    }
}
